package linked;


public class LinkedList<E> {

    private Node head;
    private int size;

    public LinkedList() {
        head = null;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return 0 == size;
    }

    public void addFirst(E e) {
//        Node newHead = new Node(e);
//        newHead.next = head;
//        head = newHead;
//        newHead = null;
        head = new Node(e, head);
        size++;
    }

    public void addLast(E e) {
        add( size,e);
    }
    public void add(int index, E e) {
        if (index < 0 && index > size) {
            throw new IllegalArgumentException("add failed,Illegal index.");
        }
        if (index ==0){
            head = new Node(e, head);
        }else{
            Node prev = head;
            for (int i = 0; i < index-1; i++) {
                prev = prev.next;
            }
            prev.next = new Node(e, prev.next);
//            prev.next = tmp.next;
//            tmp.next = prev;
        }
        size++;

//        if (isEmpty()) {
//            head = node;
//        } else {
//            Node tmp = head;
//            int i = 0;
//            while (tmp != null) {
//                if (i == index) {
//                    node.next = tmp.next;
//                    tmp.next = node;
//                    break;
//                } else {
//                    tmp = tmp.next;
//                }
//                i++;
//            }
//        }

    }

    public E get(int index){
        if (index<0 || index > size){
            throw new IllegalArgumentException("get failed,Illegal index.");
        }
        Node prev = head;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        return prev.data;
    }

    @Override
    public String toString() {
        StringBuilder ret = new StringBuilder("");
        String format = String.format("LinkedList size:%d head:", getSize());
        ret.append(format);
        Node tmp = head;
        while (tmp != null ) {
            ret.append(tmp);
            ret.append("--> ");
            tmp = tmp.next;
        }
        ret.append("null");
        return ret.toString();
    }

    private class Node {
        public E data;
        public Node next;

        public Node(E e, Node node) {
            data = e;
            next = node;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return data.toString();
        }
    }
}
